package com.hmy.uaa.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmy.uaa.bo.request.RestetPasswordRequest;
import com.hmy.uaa.bo.request.UserRequest;
import com.hmy.uaa.bo.response.*;
import com.hmy.uaa.common.security.UserOAuth2Details;
import com.hmy.uaa.dto.UserDTO;
import com.hmy.uaa.mapper.UserMapper;
import com.hmy.uaa.po.User;
import com.hmy.uaa.po.UserRoleRelation;
import com.hmy.common.exception.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleRelationService userRoleRelationService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    /**
     * 用户注册
     *
     * @param userRequest 请求参数
     */
    @Transactional
    public void register(UserRequest userRequest) {
        if (illegalMobile(userRequest)) {
            throw new ClientException("手机号已存在");
        }

        //新增用户
        User user = convertBean(userRequest);
        user.setPassword(passwordEncoder.encode(userRequest.getPassword()));
        user.setCreateTime(LocalDateTime.now());
        userMapper.insertUser(user);

        //新增角色
        Long userId = user.getId();
        userRoleRelationService.save(userId, userRequest.getRoleId());

    }

    /**
     * 修改用户
     *
     * @param userRequest 请求参数
     */
    @Transactional
    public void update(UserRequest userRequest) {
        if (illegalMobile(userRequest)) {
            throw new ClientException("手机号已存在");
        }

        //修改用户
        User user = convertBean(userRequest);
        user.setId(userRequest.getId());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);

        //修改角色
        Long userId = user.getId();
        userRoleRelationService.update(userId, userRequest.getRoleId());

    }

    /**
     * 修改密码
     *
     * @param restetPasswordRequest 新密码
     */
    @Transactional
    public void resetPassword(RestetPasswordRequest restetPasswordRequest) {

        LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>lambdaQuery()
                .eq(User::getId, restetPasswordRequest.getId());

        //修改用户
        User user = new User();
        user.setPassword(passwordEncoder.encode(restetPasswordRequest.getNewPassword()));
        user.setUpdateTime(LocalDateTime.now());

        userMapper.update(user, queryWrapper);

    }

    /**
     * 修改用户
     *
     * @param id 请求参数
     */
    @Transactional
    public void delete(Long id) {

        //删除角色
        userRoleRelationService.delete(id);

        //删除用户
        userMapper.deleteById(id);


    }

    /**
     * 查询用户
     *
     * @return Page<User>
     */
    public UserInfoResponse getUserInfo() {
        UserDTO userDTO = UserOAuth2Details.getUserDTO();

        Long roleId = null;
        List<UserRoleRelation> roleList = userRoleRelationService.selectList(Long.parseLong(userDTO.getId()));
        if (roleList.size() > 0) {
            roleId = roleList.get(0).getRoleId();
        }
        List<MenuResponse> menus = menuService.getMenuListByRoleId(roleId);


        return UserInfoResponse.builder().menus(menus).build();
    }

    /**
     * 查询用户
     *
     * @param page 分页参数
     * @param user 查询参数
     * @return Page<User> 返回数据
     */
    public Page<UserResponse> queryPage(Page<User> page, User user) {
        Long departmenId = UserOAuth2Details.getUserDTO().getDepartmentId();

        if(Objects.isNull(user.getDepartmentId())){
            user.setDepartmentId(departmenId);
        }
        return userMapper.queryPage(page, user);
    }

    /**
     * 根据部门和所属企业查询该部门下绑定短信的用户
     *
     * @param departmentId 请求部门id
     * @param companyId 所属企业id
     * @return List<User> 返回查询数据
     */
    public List<User> queryBindSmsUser(Long departmentId,Long companyId) {

        return userMapper.queryBindSmsUser(departmentId,companyId);
    }

    /**
     * 查询用户
     *
     * @param userId 用户id
     * @return User 返回用户对象
     */
    public User get(Long userId) {

        return userMapper.selectById(userId);
    }


    /**
     * 根据部门id判断用户是否存在
     * @param departmentId 部门id
     * @return boolean true：存在；false：不存在
     */
    public boolean isExistsUser(Long departmentId)
    {
        //判断该部门是否存在用户
        LambdaQueryWrapper<User> queryUserWrapper = Wrappers.<User>lambdaQuery()
                .eq(User::getDepartmentId, departmentId);
        return userMapper.selectCount(queryUserWrapper) > 0;

    }
    /**
     * 是否是非法的手机号
     */
    private boolean illegalMobile(UserRequest userRequest) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>lambdaQuery()
                .eq(User::getPhone, userRequest.getPhone());

        if (Objects.nonNull(userRequest.getId())) {
            queryWrapper.ne(User::getId, userRequest.getId());
        }
        return userMapper.selectCount(queryWrapper) > 0;
    }

    /**
     * 转换bean
     *
     * @param userRequest 请求参数
     * @return User 返回封装对象
     */
    private User convertBean(UserRequest userRequest) {
        User user = new User();
        user.setName(userRequest.getName());
        user.setPhone(userRequest.getPhone());
        user.setDepartmentId(userRequest.getDepartmentId());
        user.setEmail(userRequest.getEmail());
        user.setSex(userRequest.getSex());
        user.setSms(userRequest.getSms());
        return user;
    }

}
